// 聊天管理类
class ChatManager {
  constructor() {
    this.messagesContainer = document.getElementById("messages");
    this.messageInput = document.getElementById("messageInput");
    this.sendBtn = document.getElementById("sendBtn");
    this.socket = null;
    this.username = "用户" + Math.floor(Math.random() * 1000);

    this.init();
  }

  init() {
    this.bindEvents();
    this.connectToChat();
    this.addWelcomeMessage();
  }

  bindEvents() {
    this.sendBtn.addEventListener("click", () => this.sendMessage());

    this.messageInput.addEventListener("keypress", (e) => {
      if (e.key === "Enter") {
        this.sendMessage();
      }
    });

    this.messageInput.addEventListener("focus", () => {
      this.messageInput.placeholder = "输入消息并按回车发送...";
    });

    this.messageInput.addEventListener("blur", () => {
      this.messageInput.placeholder = "输入消息...";
    });
  }

  connectToChat() {
    // try {
    //   // 连接到聊天服务器（使用相同的WebSocket连接）
    //   this.socket = new WebSocket("ws://localhost:3003/chat");
    //   this.socket.onopen = () => {
    //     console.log("聊天连接成功");
    //     this.addSystemMessage("已连接到聊天室");
    //   };
    //   this.socket.onmessage = (event) => {
    //     try {
    //       const message = JSON.parse(event.data);
    //       this.handleChatMessage(message);
    //     } catch (error) {
    //       console.error("解析聊天消息失败:", error);
    //     }
    //   };
    //   this.socket.onclose = () => {
    //     console.log("聊天连接关闭");
    //     this.addSystemMessage("聊天连接已断开");
    //   };
    //   this.socket.onerror = (error) => {
    //     console.error("聊天连接错误:", error);
    //     this.addSystemMessage("聊天连接失败");
    //   };
    // } catch (error) {
    //   console.error("连接聊天服务器失败:", error);
    //   this.addSystemMessage("无法连接到聊天服务器");
    // }
  }

  handleChatMessage(message) {
    switch (message.type) {
      case "message":
        this.addUserMessage(
          message.username,
          message.content,
          message.timestamp
        );
        break;
      case "user-joined":
        this.addSystemMessage(`${message.username} 加入了聊天室`);
        break;
      case "user-left":
        this.addSystemMessage(`${message.username} 离开了聊天室`);
        break;
      case "online-count":
        this.updateOnlineCount(message.count);
        break;
      default:
        console.log("未知聊天消息类型:", message.type);
    }
  }

  sendMessage() {
    const content = this.messageInput.value.trim();
    if (!content) return;

    if (!this.socket || this.socket.readyState !== WebSocket.OPEN) {
      this.addSystemMessage("聊天连接未建立，无法发送消息");
      return;
    }

    const message = {
      type: "message",
      username: this.username,
      content: content,
      timestamp: new Date().toISOString(),
    };

    this.socket.send(JSON.stringify(message));
    this.messageInput.value = "";

    // 添加自己的消息到界面（带有特殊样式）
    this.addUserMessage(this.username, content, message.timestamp, true);
  }

  addUserMessage(username, content, timestamp, isOwn = false) {
    const messageDiv = document.createElement("div");
    messageDiv.className = `message ${isOwn ? "own-message" : ""}`;

    const time = new Date(timestamp).toLocaleTimeString("zh-CN", {
      hour: "2-digit",
      minute: "2-digit",
    });

    messageDiv.innerHTML = `
            <span class="username">${this.escapeHtml(username)}:</span>
            <span class="content">${this.escapeHtml(content)}</span>
            <span class="time">${time}</span>
        `;

    this.messagesContainer.appendChild(messageDiv);
    this.scrollToBottom();
  }

  addSystemMessage(content) {
    const messageDiv = document.createElement("div");
    messageDiv.className = "message system-message";

    const time = new Date().toLocaleTimeString("zh-CN", {
      hour: "2-digit",
      minute: "2-digit",
    });

    messageDiv.innerHTML = `
            <span class="content system">${this.escapeHtml(content)}</span>
            <span class="time">${time}</span>
        `;

    this.messagesContainer.appendChild(messageDiv);
    this.scrollToBottom();
  }

  addWelcomeMessage() {
    this.addSystemMessage(`欢迎 ${this.username}！`);
    this.addSystemMessage("在这里与其他观众互动吧！");
  }

  updateOnlineCount(count) {
    // 可以在这里更新在线人数显示
    console.log("在线人数:", count);
  }

  scrollToBottom() {
    setTimeout(() => {
      this.messagesContainer.scrollTop = this.messagesContainer.scrollHeight;
    }, 100);
  }

  escapeHtml(text) {
    const map = {
      "&": "&amp;",
      "<": "&lt;",
      ">": "&gt;",
      '"': "&quot;",
      "'": "&#039;",
    };
    return text.replace(/[&<>"']/g, (m) => map[m]);
  }

  setUsername(newUsername) {
    this.username = newUsername;
  }

  disconnect() {
    if (this.socket) {
      this.socket.close();
      this.socket = null;
    }
  }
}
